# coding:utf-8
from pathlib import Path
from typing import Union, List, Any

from PyQt6.QtCore import QThreadPool
from PyQt6.QtWidgets import QWidget, QFileDialog
from qfluentwidgets import GroupHeaderCardWidget, FluentIcon, PushButton, PrimaryPushButton, InfoBar
from docx2pdf import convert

from common import OfficeIcon
from components import BaseScrollArea, FileListSettingCard


def convert_word_to_pdf(
        input_paths: Union[str, Path, List[str], List[Path]],
        output_path: str = None,
):
    pool = QThreadPool.globalInstance()
    pool.setMaxThreadCount(4)
    if isinstance(input_paths, (str, Path)):
        input_paths = [input_paths]
    for input_path in input_paths:
        if isinstance(input_path, str):
            input_path = Path(input_path)
        if output_path is None:
            output_file = Path(input_path).with_suffix('.pdf')
        else:
            output_file = Path(output_path) / f'{input_path.stem}.pdf'
        pool.start(lambda: convert(input_path.as_posix(), output_file.as_posix()))

    pool.waitForDone()


class WordToPdfView(BaseScrollArea):
    title = 'Word 转 PDF'
    description = '将 Word 文件转换为 PDF 文件'
    object_name = 'WordToPdfView'
    icon = OfficeIcon.PDF3

    def __init__(self, parent: QWidget = None):
        super().__init__(parent)
        self.filesCard = FileListSettingCard(
            icon=OfficeIcon.WORD4,
            title='Word 文件(目前只支持docx格式)',
            directory='Word文件(*.docx)',
            parent=self,
        )
        self.saveBtn = PushButton(FluentIcon.FOLDER, '选择路径', self)
        self.startBtn = PrimaryPushButton(FluentIcon.PLAY, '开始转换', self)
        self.groupHeader = GroupHeaderCardWidget('基本设置', self)
        self.saveGroup = self.groupHeader.addGroup(
            FluentIcon.SAVE,
            '保存路径',
            '选择保存路径',
            self.saveBtn
        )
        self.groupHeader.addGroup(
            FluentIcon.PLAY_SOLID,
            '开始转换',
            '开始将Word文件转换为PDF文件',
            self.startBtn
        )

        self.__initWidget()

    def __initWidget(self):
        self.setReturnVisible(True)
        self.scrollLayout.addWidget(self.filesCard)
        self.scrollLayout.addWidget(self.groupHeader)

        self.startBtn.clicked.connect(self.__startConvert)
        self.saveBtn.clicked.connect(self.__showFolderDialog)

    def __showFolderDialog(self):
        folder = QFileDialog.getExistingDirectory(self, '选择文件夹', './')
        if folder:
            self.saveGroup.setContent(folder)

    def __startConvert(self):
        input_paths = self.filesCard.files
        output_path = self.saveGroup.content()
        if not output_path or not input_paths:
            InfoBar.warning('', '请选择文件和保存路径', duration=2000, parent=self)
            return
        self.setDialogTitle('Word 转 PDF')
        self.setDialogContent('正在将Word文件转换为PDF文件，请稍候...')
        self.load(convert_word_to_pdf, input_paths, output_path)

    def onFuncSuccess(self, result: Any):
        InfoBar.success('转换成功', f'转换成功，文件保存至{self.saveGroup.content()}', duration=2000, parent=self)
